// 这是通过appTool自动生成的rpcx代码，请勿修改
package exampleRpc

import (
	"context"
	"errors"

	"github.com/sirupsen/logrus"
	"github.com/smallnest/rpcx/client"
)

var (
	gClient                client.XClient
	discoverys             []client.ServiceDiscovery
	lg                     = logrus.New().WithField("tag", "rpc")
	ClientInitDoneCallback func(client.XClient)
)
var ArithSev *arithRpcxClient

func RpcxClients(discovery client.ServiceDiscovery, failMode client.FailMode, selectMode client.SelectMode, option client.Option) {
	if ArithSev == nil {
		d, _ := discovery.Clone("example.arithSev")
		discoverys = append(discoverys, d)
		ArithSev = &arithRpcxClient{client: client.NewXClient("example.arithSev", failMode, selectMode, d, option)}
		clientInitDone(ArithSev.client)
	}
	if gClient == nil {
		d, _ := discovery.Clone("example.globalFun")
		discoverys = append(discoverys, d)
		gClient = client.NewXClient("example.globalFun", failMode, selectMode, d, option)
		clientInitDone(gClient)
	}
}
func RpcxClose() {
	if ArithSev != nil {
		ArithSev.client.Close()
		ArithSev = nil
	}
	if gClient != nil {
		gClient.Close()
		gClient = nil
	}
	for _, d := range discoverys {
		d.Close()
	}
	discoverys = nil
}
func SetLogger(l *logrus.Entry) {
	lg = l
}
func GetRpcClient() client.XClient {
	return gClient
}
func clientInitDone(c client.XClient) {
	if ClientInitDoneCallback != nil {
		ClientInitDoneCallback(c)
	}
}

// RpcHealthCheck RPC服务状态检测
func RpcHealthCheck() (bool, error) {
	var err error
	var resp string
	if gClient == nil {
		err = errors.New("gClient尚未初始化")
	} else {
		err = gClient.Call(context.Background(), "RpcServerHealth", nil, &resp)
	}
	if err != nil {
		if lg != nil {
			lg.Errorf("[服务健康检测]RPC调用错误:%s", err.Error())
		}
		return false, err
	}
	if resp != "example" {
		if lg != nil {
			lg.Error("[服务健康检测]RPC调用错误:返回值异常")
		}
		return false, errors.New("返回值异常,目标值:example,返回值:" + resp)
	}
	return true, nil
}
